<?php
namespace control;
/*
*考勤规则类
*/

class clockRuleClass extends adIndexClass
{
	private const page  = 'clockRule';
	private const table = 'clock_rule';
	private const title = '考勤规则';
	public array $clockType = [];

	public function __construct()
	{
		parent::__construct();
		$this->clockType = ['1' => L('clock.table.gdsjsxb'), '2' => L('clock.table.abcsxb'), '3' => L('clock.table.zysxb')];
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('clock.table.kao_qin_zu') => text(array("name" => "team")),
                    L('clock.table.lei_xing')     => select(array("name" => "type", "option" => $this->clockType)),
                    L('clock.table.cjrq') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    L('clock.table.zhuang_tai') => select(array("name" => "state", "option" => ['启用', '停用'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>" . L('clock.table.addNew') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('clock.table.shan_chu') . "</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>" . L('clock.table.enable') . "</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>" . L('clock.table.unEnable') . "</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
	}

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'team'      => [
                        'name'  => L('clock.table.kao_qin_zu'),
                        'width' => 300,
                    ],
                    'type' => [
                        'name'  => L('clock.table.lei_xing'),
                        'width' => 300,
                    ],
                    'people'  => [
                        'name'  => L('clock.table.ren_shu'),
                        'width' => 300,
                    ],
                    'time'         => [
                        'name'  => L('clock.table.cjrq'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('clock.table.zhuang_tai'),
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"team" => $this->post('team'),//试卷编号
		);
		//全等查询数组
		$equal = array(
			"state" => $this->post('state'),//状态
			"type"  => $this->post('type'),//类型
		);
		$and   = "";
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'));
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => L('clock.table.clockRuleInfo'), "click" => "newIframe('" . L('clock.table.clockRuleInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "type":
                        $row[] = $this->clockType[$array['type']];
                        break;
                    case "people":
                        $people   = $array['member'] ? count(explode(',', $array['member'])) : 0;
                        $row[] = $people;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitch()
	{
		$type     = $this->post('type');
		$classify = $this->post('classify');
		$formName = 'listForm';
		$typeText = match ($type) {
			'启用'  => L('topic.table.enable'),
			default => L('topic.table.unenable'),
		};
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					L('topic.table.tip') . "：" => L('topic.table.changeTip') . "：" . $typeText,
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $type)) . hidden(array('name' => 'classify', 'value' => $classify)),
		));
		//返回
		return $this->layer(array("title" => L('clock.table.ztqh'), "height" => 165, "html" => $html, 'formTwo' => $formName));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit()
	{
		$type     = $this->post('type');
		$classify = $this->post('classify');
		if ($classify == 'topic') {
			$idArr = $this->post('mxId');
		} else {
			$idArr = $this->post('listId');
		}
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('clock.table.rule_edit_permission');
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = L('clock.table.qxzsj');
		} elseif (!in_array($type, ['启用', '停用'])) {
			$json['warn'] = L('clock.table.lei_xing_cuo_wu');
		} else {
			$json['warn'] = update(array('table' => self::table, 'field' => ['state' => $type], 'where' => " id in ('" . implode("','", $idArr) . "')"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$operate = match ($type) {
					'启用'  => L('topic.table.enable'),
					default => L('topic.table.unenable'),
				};
				$text    = str_replace(['{{staffName}}', '{{state}}'], [$this->control['name'], $operate], L('clock.table.rule_enable_text')) . implode(",", $idArr);
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id       = $this->post('id');
        $info     = query(self::table, " id = '" . $id . "' ");

        /********迟到早退扣款********/
        $clockRuleTr = '';
        $result      = find(array('table' => 'clock_rule_detail', 'where' => " orderId = '$info[id]' order by list asc"));
        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span  class='btn-borderless' style='margin-top: 0' onclick='addRow(this)'>" . L('clock.table.add') . "</span>";
                } else {
                    $button = "<span class='btn-borderless' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span>";
                }
                $clockRuleTr .=
                    "<div style='height: 40px'><ul><li style='float: left'>" . L('clock.table.less') . "：</li><li style='float: left'>" . text(array('name' => 'minute[]', 'value' => $array['minute'], 'class' => 'width200', 'unit' => L('clock.table.fen_zhong'))) .
                    "</li><li style='float: left'>&emsp;" . L('clock.table.decMoney') . "：</li><li style='float: left'>" . text(array('name' => 'money[]', 'value' => $array['money'], 'class' => 'width200', 'unit' =>  static::$unit )) .
                    "</li><li style='float: left'>{$button}</li></ul></div>";
            }
        } else {
            $clockRuleTr =
                "<div style='height: 40px'><ul><li style='float: left'>" . L('clock.table.less') . "：</li><li style='float: left'>" . text(array('name' => 'minute[]', 'class' => 'width200', 'unit' => L('clock.table.fen_zhong'))) .
                "</li><li style='float: left'>&emsp;" . L('clock.table.decMoney') . "：</li><li style='float: left'>" . text(array('name' => 'money[]', 'class' => 'width200', 'unit' =>  static::$unit )) .
                "</li><li style='float: left'><span class='btn-borderless' onclick='addRow(this)'>" . L('clock.table.add') . "</span></li></ul></div>";
        }
        /********打卡时间********/
        $clockTimeTr = '';
        $result      = find(array('table' => 'clock_rule_time', 'where' => " orderId = '$info[id]' order by list asc"));
        $option    = [];//小时选项
        $startHour = 5;
        $flag      = false;//次日标志
        for ($i = 0; $i < 24; $i++) {
            if ($startHour == 24) {
                $startHour = 0;
                $flag      = true;
            }
            if ($flag) {
                if ($startHour < 5) {
                    $option['next-' . $startHour] = '次日' . $startHour;
                }
            } else {
                $option['now-' . $startHour] = $startHour;
            }
            $startHour++;
        }

        $minuteOption = [];//分钟选项
        for ($i = 0; $i < 60; $i++) {
            $minuteOption[$i] = sprintf("%02d", $i);
        }

        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span class='btn-borderless' onclick='addTimeRow(this)'>" . L('clock.table.add') . "</span>";
                } else {
                    $button = "<span class='btn-borderless' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span>";
                }
                $startItem   = explode(':', $array['startTime']);
                $startType   = $array['startType'] == 1 ? 'next-' : 'now-';
                $endItem     = explode(':', $array['endTime']);
                $endType     = $array['endType'] == 1 ? 'next-' : 'now-';
                $clockTimeTr .=
                    "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'value' => $startType . $startItem[0], 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => $startItem[1], 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
                    select(array('name' => 'endHour[]', 'value' => $endType . $endItem[0], 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'endMinute[]', 'value' => $endItem[1], 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'>{$button}</li></ul></div>";
            }
        } else {
            $clockTimeTr =
                "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'value' => '', 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => '', 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
                select(array('name' => 'endHour[]', 'value' => '', 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'endMinute[]', 'value' => '', 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'><span class='btn-borderless' onclick='addTimeRow(this)'>" . L('clock.table.add') . "</span></li></ul></div>";
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('clock.table.lei_xing') . "：" => radio(["name" => "type", 'value' => $this->clockType, "checked" => $info['type']]),
                ],
                [
                    must . L('clock.table.kao_qin_zu') . "：" => text(["name" => "team", "value" => $info['team']]),
                    must . L('clock.table.gong_zuo_ri') . "：" => selectMultiple(["name" => "workDayId", 'title' => L('clock.table.gong_zuo_ri'), 'table' => " work_day", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'select', "value" => $info['workDayId']]),
                ],
                [
                    must . L('clock.table.syry') . "：" => componentClass::staffSelector($info['selector']),
                ],
                [
                    must . L('clock.table.sxbsj') . "：" => "<div class='clockTimeDiv'>" . $clockTimeTr . "</div>",
                ],
                [
                    must . L('clock.table.cdztkk') . "：" => "<div class='clockRuleDiv'>" . $clockRuleTr . "</div>",
                ],

                [
                    must . L('clock.table.kgkk') . "：" => text(["name" => "absenceMoney", "class" => "width150", 'unit' =>  static::$unit  . '/次', "value" => $info['absenceMoney']]),
                    L('clock.table.monthMax') . "：" => text(["name" => "maxNum", 'unit' => '次'. componentClass::tipComponent('-1表示无限制'), "value" => $info['maxNum']]),
                ],
                [
                    L('clock.table.allowTime') . "：" => text(["name" => "maxDay", "class" => "width150", 'unit' => '天'. componentClass::tipComponent('-1表示无限制'), "value" => $info['maxDay']]),
                    "生效时间：" => text(["name" => "ruleStartTime", 'laydate' => [], "value" => $info['id']?date('Y-m-d',strtotime($info['startTime'])):$this->date]),
                ],
            ],
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 450, "html" => $html));
    }

	public function js(): string
	{
		return <<<eof
<script>
$(function (){
    setRadio();
})
$("[name='type']").click(function() {
   setRadio();
});

function setRadio(){
    let type = $("input[name='type']:checked").val();
    if (type==1){
         $(".clockTimeDiv").parent().parent().css('display','flex');
        $(".clockRuleDiv").parent().parent().css('display','flex');
    }else if(type==2){
         $(".clockTimeDiv").parent().parent().css('display','none');
        $(".clockRuleDiv").parent().parent().css('display','flex');
    }else if(type ==3){
        $(".clockTimeDiv").parent().parent().css('display','none');
        $(".clockRuleDiv").parent().parent().css('display','none');
    }
}
function addRow(e){
    let total = 0;
    $(".clockRuleDiv ul").each(function (i){
        total++;
    });
    if (total>4){
        warn('最多设置5条');

    }else{
         $.post(root+'control/adIndex.html?cla=clockRule&fun=addRow',{},function (res){
            $('.clockRuleDiv').append(res.data.html);
        },'json')
    }

}
function addTimeRow(e){
    let total = 0;
    $(".clockTimeDiv ul").each(function (i){
        total++;
    });
    if (total>4){
        warn('最多设置5条');

    }else{
         $.post(root+'control/adIndex.html?cla=clockRule&fun=addTimeRow',{},function (res){
                $('.clockTimeDiv').append(res.data.html);
            },'json')
        }

}
function decRow(e){
    $(e).parent().parent().parent().remove();
}
</script>
eof;
	}

	/**
	 * 添加迟到早退扣款
	 *
	 * @return bool|string
	 */
	public function addRow()
	{
		$json['data']['html'] = "<div style='height: 40px'><ul><li style='float: left'>" . L('clock.table.less') . "：</li><li style='float: left'>" . text(array('name' => 'minute[]', 'class' => 'width200', 'unit' => L('clock.table.fen_zhong'))) .
		                        "</li><li style='float: left'>&emsp;" . L('clock.table.decMoney') . "：</li><li style='float: left'>" . text(array('name' => 'money[]', 'class' => 'width200', 'unit' =>  static::$unit )) .
		                        "</li><li style='float: left'><span class='btn-borderless' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span></li></ul></div>";
		return json_encode($json, 320);
	}

	/**
	 * 添加打卡时间
	 */
	public function addTimeRow()
	{
		$option    = [];//小时选项
		$startHour = 5;
		$flag      = false;//次日标志
		for ($i = 0; $i < 24; $i++) {
			if ($startHour == 24) {
				$startHour = 0;
				$flag      = true;
			}
			if ($flag) {
				if ($startHour < 5) {
					$option['next-' . $startHour] = '次日' . $startHour;
				}
			} else {
				$option['now-' . $startHour] = $startHour;
			}
			$startHour++;
		}

		$minuteOption = [];//分钟选项
		for ($i = 0; $i < 60; $i++) {
			$minuteOption[$i] = sprintf("%02d", $i);
		}
		$json['data']['html'] = "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'value' => '', 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => '', 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
		                        select(array('name' => 'endHour[]', 'value' => '', 'class' => 'width100', 'title' => '时', 'option' => $option)) . select(array('name' => 'endMinute[]', 'value' => '', 'class' => 'width100', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'><span class='btn-borderless' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span></li></ul></div>";
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function editEdit()
	{
		$id             = $this->post('id') ?: self::getId();
		$minuteArr      = $this->post('minute');//迟到早退分钟
		$moneyArr       = $this->post('money'); //扣款
		$startHourArr   = $this->post('startHour');
		$startMinuteArr = $this->post('startMinute');
		$endHourArr     = $this->post('endHour');
		$endMinuteArr   = $this->post('endMinute');

		$field      = [
			'team'         => $this->post('team'),
			'type'         => $this->post('type'),
			'workDayId'    => $this->post('workDayId'),
			'selector'     => $this->post('staff')[0] ?? '',//员工选择器
			'absenceMoney' => $this->post('absenceMoney'),
			'maxNum'       => $this->post('maxNum'),
			'maxDay'       => $this->post('maxDay'),
            'startTime'=>$this->post('ruleStartTime')?:$this->date,
			'updateTime'   => $this->time,
		];
		$annotation = [
			'team'         => L('clock.table.kao_qin_zu'),
			'type'         => L('clock.table.lei_xing'),
			'workDayId'    => L('clock.table.gong_zuo_ri'),
			'selector'     => L('clock.table.syry'),
			'absenceMoney' => L('clock.table.kgkk'),
		];
		$rules      = [
			'team'         => 'required',
			'type'         => 'required',
			'workDayId'    => 'required',
			'selector'     => 'required',
			'absenceMoney' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$staff           = componentClass::returnStaffId($field['selector']);
		$field['member'] = implode(',', $staff);
		$warn            = $this->checkStaff($staff, $id,$field['workDayId']);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = L('clock.table.rule_edit_permission');
		} elseif (!empty($warn)) {
			$json['warn'] = str_replace(['{{name}}'], [$warn], L('clock.table.yuan_gong'));
		} else {
			$where = " id = '$id' ";
			$info  = query(self::table, $where);
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'AR',
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'        => $id,
					'orderNo'   => $userNo,
					'stid'      => $this->control['stid'],
					'state'     => '启用',
//					'startTime' => $this->time,
					'time'      => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				delete(array('table' => 'clock_rule_detail', 'where' => " orderId = '$id'"));
				delete(array('table' => 'clock_rule_time', 'where' => " orderId = '$id'"));
				if ($field['type'] == 1) {
					//类型为固定上下班时间  删除原来的数据
					if (is_array($startHourArr)) {
						foreach ($startHourArr as $k => $val) {
							$item    = explode('-', $val);
							$endHour = explode('-', $endHourArr[$k]);
							insert(array(
								'table' => 'clock_rule_time',
								'field' => [
									'id'        => self::getId(),
									'orderId'   => $id,
									'startType' => $item[0] == 'next' ? 1 : 0,
									'startTime' => $item[1] . ':' . $startMinuteArr[$k],
									'endType'   => $endHour[0] == 'next' ? 1 : 0,
									'endTime'   => $endHour[1] . ':' . $endMinuteArr[$k],
									'time'      => $this->time,
								],
							));
						}
					}
				}
				if ($field['type'] == 1 || $field['type'] == 2) {
					//固定上下班时间 或 按班次上下班
					if (is_array($minuteArr)) {
						foreach ($minuteArr as $k => $val) {
							insert(array(
								'table' => 'clock_rule_detail',
								'field' => [
									'id'      => self::getId(),
									'orderId' => $id,
									'minute'  => $val,
									'money'   => $moneyArr[$k],
									'time'    => $this->time,
								],
							));
						}
					}
				}

				if ($field['type'] == 2 && static::total(['table' => 'roster', 'where' => " and clockRuleId = '$id'"]) <= 0) {
					//创建排班表数据
					$userNo = codeTemplateClass::generateCode('scheduler', [
						'prefix' => 'SS',
						'table'  => 'roster',
						'field'  => 'orderNo',
						'where'  => '',
					], []);
					insert(array(
						'table' => 'roster',
						'field' => [
							'id'          => self::getId(),
							'clockRuleId' => $id,
							'orderNo'     => $userNo,
							'time'        => $this->time,
						],
					));
				}
				//添加日志
				$text = str_replace(['{{staffName}}', '{{team}}', '{{id}}'], [$this->control['name'], $field['team'], $id], L('clock.table.rule_edit_text'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}

    /**
     * 检查是否有员工在其他考勤规则里
     *
     * @param $staff
     * @param $id
     * @param string $wrokDayId
     * @return bool|string
     */
	public function checkStaff($staff, $id,$wrokDayId=''): bool|string
	{
		$name = '';
		$where = '';
		if ($wrokDayId){
		    $where.=" and workDayId ='$wrokDayId'";
        }
		foreach ($staff as $stid) {
			if (static::total(array('table' => self::table, "where" => " and member like '%{$stid}%' and id !='{$id}' ".$where)) > 0) {
				$staff = query('staff', "stid = '$stid'");
				$name  = $staff['name'];
				break;
			}
		}
		return $name;
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = L('clock.table.no_rule');
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
			if ($this->power(self::page, "edit")) {
				//按钮
				$button[] = [
					"name"  => L('clock.table.bian_ji'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "del")) {
				//按钮
				$button[] = [
					"name" => L('clock.table.shan_chu'),
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			//工作日
			$workDay = query('work_day', " id = '$info[workDayId]'");
			//打卡时间
			$clockTime = find(['table' => 'clock_rule_time', 'field' => " group_concat(CONCAT_WS('-',any_value(startTime),if(any_value(endType),CONCAT_WS('','次日',any_value(endTime)),any_value(endTime)))) as clockTime", 'single' => " orderId = '$info[id]' group by orderId"]);
			//迟到早退扣款
			$decResult = find(['table' => 'clock_rule_detail', 'field' => " group_concat(CONCAT(any_value(minute),L('clock.table.fen_zhong'),any_value(money),'" . static::$unit . "')) as result", 'single' => " orderId = '$info[id]' group by orderId"]);

			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				"详细信息" => array(
					array(
                        L('clock.table.lei_xing')    => $this->clockType[$info['type']],
						L('clock.table.kao_qin_zu')  => $info['team'],
						L('clock.table.gong_zuo_ri') => $workDay['name'],
                        L('clock.table.sxbsj')              => $clockTime['clockTime'] ?? '',

					),
					array(
						L('clock.table.monthMax') . "(次)"  => $info['maxNum'] . componentClass::tipComponent('-1表示无限制'),
						L('clock.table.allowTime') . "(天)" => $info['maxDay'] . componentClass::tipComponent('-1表示无限制'),
                        L('clock.table.cdztkk')      => $decResult['result'] ?? '',
                        L('clock.table.absenteeism') => $info['absenceMoney'],
					),
					array(
                        L('clock.table.syry') => componentClass::showSelector($info['selector']),

					),
				),
				L('clock.table.xi_tong_xin_xi') => array(
					array(
						L('clock.table.kqgzbh')          => $info['orderNo'],
						L('clock.table.chuang_jian_ren') => self::findStaff($info['stid']),
						L('clock.table.cjsj')            => $info['time'],
                        L('clock.table.gxsj')       => $info['updateTime'],
					),
					array(
						L('clock.table.sxsj')       => self::null($info['startTime']),
						L('clock.table.zhuang_tai') => $info['state'],
					),
				),
			));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate()
	{
		$act = $this->post('act') ?? '';
		$pwd = false; // 需要密码
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = L('clock.table.delRule');
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = L('clock.table.nmzscdzx');
		} elseif (empty($array)) {
			$json['warn'] = L('clock.table.nygsjdmzxzn');
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] != '停用') {
					$warn = L('clock.table.stop_del_warn');
				} else {
					//删除排班班次打卡时间表
					delete(array("table" => "clock_rule_time", "where" => " orderId in (select id from `roster_detail` where orderId in (select id from roster where clockRuleId = '$id'))"));
					//删除排班班次表
					delete(array("table" => "roster_detail", "where" => " orderId in (select id from roster where clockRuleId = '$id') "));
					//删除排班表
					delete(array("table" => "roster", "where" => " clockRuleId = '$id' "));

					//删除打卡时间
					delete(array("table" => "clock_rule_time", "where" => " orderId = '$id' "));
					//删除迟到早退扣款
					delete(array("table" => "clock_rule_detail", "where" => " orderId = '$id' "));
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					//返回
					$warn = L('clock.table.sccg');
					$x++;
				}
				$text .= str_replace(['{{team}}', '{{id}}'], [$info['team'], $id], L('clock.table.rule_del_text')) . $warn . "。<br>";
			}
			//添加日志
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('clock.table.rule_del_log')) . "<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clock.table.rule_del_warn'));
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}
